import { Injectable, ElementRef, Renderer2, OnChanges } from '@angular/core'; // ElementRef, Renderer2
import { CacheService } from '@services/cache.service';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Media, MediaObject } from '@ionic-native/media/ngx';

@Injectable()
export class AlarmAudioService {
    audioList; // 未播放的语音列表
    myAudio;
    currentItem;  // 当前播放
    defaultHeaders;
    InitData = [];
    el;
    render;
    service;
    Audio;

    constructor(
        private cache: CacheService,
        private http: HttpClient,
        private media: Media
    ) {
    }

    changeStatus() {
        console.log(this.currentItem)
        if (this.currentItem) {
            return true;
        } else {
            return false;
        }
    }

    getStatus() {
        console.log(this.myAudio);
        return this.myAudio;
    }

    stopPlay() {
        this.currentItem = undefined;
        this.Audio.setVolume(0.0);
    }

    beginPlay() {
        this.Audio.setVolume(1.0);
    }


    mergeList(list) {
        const obj = {
            voiceUrl: '',
            content: '',
            isPlay: false,
            playFinish: false,
        };
        obj.content = list;
        obj.isPlay = false;     // 是否开始播了
        obj.playFinish = false; // 是否播完了
        this.InitData.unshift(obj);
        console.log(this.InitData);
    }


    // 获取未播放的列表
    getAudioList() {
        const newArr = [];
        this.InitData.forEach(function (each) {
            if (each.isPlay === false) {
                newArr.push(each);
            }
        });
        return newArr;
    }

    // 将本条语音设置成已播放
    setPlayState(content) {
        if (this.InitData.length) {
            for (let i = 0; i < this.InitData.length; i++) {
                if (this.InitData[i].content === content) {
                    this.InitData[i].isPlay = true;
                }
            }
        }
        console.log('设置成已播放后', this.InitData);
    }


    audioPlayInit() {
        const arr = this.getAudioList();
        this.currentItem = arr.pop();
        console.log(this.currentItem);
        this.startplay();
    }

    startplay() {
        console.log('开始播放', this.currentItem);
        if (this.currentItem) {
            console.log(this.currentItem.content);
            this.getAudioUrl(this.currentItem.content).subscribe(data => {
                if (data) {
                    console.log(data);
                    this.currentItem.voiceUrl = data;
                    const file: MediaObject = this.media.create(this.currentItem.voiceUrl);
                    console.log(file)
                    this.Audio = file;
                    console.log('播放器', Audio)
                    file.play();
                    file.onStatusUpdate.subscribe(status => {
                        console.log(status);
                        if (status === 4) {
                            file.release();
                        }
                    });
                    file.onSuccess.subscribe(() => {
                        console.log('播放成功');
                        this.playEndedHandler();
                    });
                    file.onError.subscribe((error) => {
                        console.log('播放错误,重新播放', error);
                        this.playEndedHandler();
                    });
                    this.setPlayState(this.currentItem.content);
                } else {
                    console.log('获取语音失败');
                    this.currentItem = undefined;
                }
            });
        }
    }

    // 上一个播放完毕后调用此方法
    playEndedHandler() {
        this.currentItem.playFinish = true;
        console.log('播放完成', this.currentItem)
        const arr = this.getAudioList();
        this.currentItem = arr.pop();
        console.log(this.currentItem)
        if (this.currentItem) {
            this.getAudioUrl(this.currentItem.content).subscribe(res => {
                if (res) {
                    this.Audio.voiceUrl = res;
                    const file: MediaObject = this.media.create(this.currentItem.voiceUrl);
                    this.Audio = file;
                    file.play();
                    file.onStatusUpdate.subscribe(status => {
                        console.log(status);
                        if (status === 4) {
                            file.release();
                        }
                    });
                    file.onSuccess.subscribe(() => {
                        console.log('播放成功');
                        this.playEndedHandler();
                    });
                    file.onError.subscribe((error) => {
                        console.log('播放错误重新播放', error);
                        this.playEndedHandler();
                    });
                    this.setPlayState(this.currentItem.content);
                } else {
                    console.log('获取语音失败');
                    this.currentItem = undefined;
                }
            });
        } else {
            console.log('最后一条');
            this.currentItem = undefined;
        }
    }

    getAudioUrl(content): Observable<any> {
        console.log(this.cache.getClientToken())
        const url = `http://file.eegrid.com/api/OnlineTts/GetUrl`;
        const ret = this.http.post(
            url,
            {
                content: content,
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    Ver: 'android_1.0',
                    Token: this.cache.getClientToken()
                },
            }
        );
        return ret;
    }

}
